package com.yyq.gxdc.controller;

import com.yyq.gxdc.bean.Result;

import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * @version 1.0
 */
@Api(tags = "上传文件")
@CrossOrigin
@RestController
@RequestMapping("")
public class UploadController {


    @PostMapping(value = "/uploadImg")
    public Result<Object> uploadImg(@RequestParam("file")MultipartFile file,
                                    HttpServletRequest request) throws Exception {
        //获取当前时间
        LocalDateTime localDateTime = LocalDateTime.now();
        DateTimeFormatter dateTimeFormatter =   DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String time = localDateTime.format(dateTimeFormatter);
        //创建图片保存路径
        String imgPath = "\\src\\main\\resources\\static\\Imgs\\newImgs\\";
        String path = System.getProperty("user.dir") + imgPath;
        String uuid = UUID.randomUUID().toString();
        String fileName = uuid+file.getOriginalFilename();
        File filePath=new File(path+fileName);
        if(!filePath.exists()){//如果文件夹不存在
            filePath.mkdirs();//创建文件夹
        }
        file.transferTo(filePath);
        //保存  "/Imgs/EssayImg/"+fileName
        String upImgPath = "/Imgs/newImgs/"+fileName;
        return Result.ok(upImgPath);
    }

}
